package com.kfm.login.interceptor;

import com.kfm.login.util.Constant;
import com.kfm.login.util.IPUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 黑名单拦截器 确认访问的 ip 是否在黑名单
 */
@Component
public class BlackInterceptor implements HandlerInterceptor {

    @Resource
    RedisTemplate<String, Integer> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取IP，判断IP是否在黑名单
        String ip = IPUtils.getIpAddress(request);
        String key = Constant.REDIS_BLACK_PREFIX + ip;
        Integer i = redisTemplate.opsForValue().get(key);
        System.out.println(i);
        if (i != null) { // 在黑名单中
            response.sendRedirect("/error");
            return false;
        }
        return true;
    }
}
